package com.kejizhentan.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.kejizhentan.repository.DepartmentRepository;
import com.kejizhentan.service.DepartmentService;
import com.kejizhentan.yygh.model.hosp.Department;
import com.kejizhentan.yygh.vo.hosp.DepartmentQueryVo;
import com.kejizhentan.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author shikaifeng
 * @Date 2022/9/28 15:55
 * @Version 1.0
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void save(Map<String, Object> paramMap) {
        // paramMap 转换成 Department 对象
        String paramMapString = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(paramMapString, Department.class);

        // 根据医院编号和科室编号查询是否存在
        Department departmentExist = departmentRepository
                .getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());

        // 不存在添加 存在更新
        if (!ObjectUtils.isEmpty(departmentExist)) {
            departmentExist.setCreateTime(new Date());
            departmentExist.setIsDeleted(0);
            departmentRepository.save(departmentExist);
        } else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }

    @Override
    public void remove(String hoscode, String depcode) {
        // 根据医院编号和科室编号查询科室信息
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (!ObjectUtils.isEmpty(department)) {
            // 调用删除方法
            departmentRepository.deleteById(department.getId());
        }
    }


    @Override
    public Page<Department> findPageDepartment(int page, int limit, DepartmentQueryVo departmentQueryVo) {
        // 创建 Pageable对象，设置当前页和每页记录数（0是第一页）
        Pageable pageable = PageRequest.of(page - 1, limit);
        // 创建 Example 对象
        ExampleMatcher matcher = ExampleMatcher
                .matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);

        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);

        Example<Department> example = Example.of(department, matcher);
        return departmentRepository.findAll(example, pageable);
    }

    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        // 创建 list 集合，用于最终数据封装
        List<DepartmentVo> result = new ArrayList<>();

        // 根据医院编号，查询所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example<Department> example = Example.of(departmentQuery);
        // 所有科室列表信息
        List<Department> departmentList = departmentRepository.findAll(example);

        // 根据大科室编号 bigcode 进行分组，获取每个大科室里面下级子科室
        Map<String, List<Department>> departmentMap = departmentList
                .stream()
                .collect(Collectors.groupingBy(Department::getBigcode));

        // 遍历 departmentMap
        for (Map.Entry<String, List<Department>> entry : departmentMap.entrySet()) {
            // 大科室编号
            String big_code = entry.getKey();
            // 大科室编号对应的全部数据
            List<Department> depList = entry.getValue();

            // 封装大科室
            DepartmentVo bigVo = DepartmentVo
                    .builder()
                    .depcode(big_code)
                    .depname(depList.get(0).getDepname())
                    .build();

            // 封装小科室
            List<DepartmentVo> children = new ArrayList<>();
            for (Department department : depList) {
                DepartmentVo smallVo = DepartmentVo
                        .builder()
                        .depcode(department.getDepcode())
                        .depname(department.getDepname())
                        .build();
                // 封装到 children
                children.add(smallVo);
            }
            // 把小科室 list 集合封装到大科室 children 里
            bigVo.setChildren(children);
            // 放到醉蛛的 result 中去
            result.add(bigVo);
        }
        return result;
    }

    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (!ObjectUtils.isEmpty(department)) {
            return department.getDepname();
        }
        return null;
    }

    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
    }
}
